//
//  NXFifthStepViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/4.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "NXFifthStepViewController.h"
#import "ShowPicViewController.h"
#import "NXSixthStepViewController.h"
#import "NXSeventhStepViewController.h"
#import "UIImage+fixOrientation.h"
#import "TakeMultiPhotoViewController.h"
#import "TZImagePickerController.h"
@interface NXFifthStepViewController ()<TZImagePickerControllerDelegate>
{
    NSInteger currentRowIndex;
    NSMutableArray *selectedAssets;
}
@end

@implementation NXFifthStepViewController
static const NSString * KEY_STEP  = @"step5";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"setp5 record === %@", self.NewRecordArray.firstObject.getDetailDict);
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _maintableview=[[UITableView alloc]initWithFrame:CGRectMake(10, 64, fWidth_Current-20, fHeight_Current-64-50)];
    _maintableview.backgroundColor = [UIColor clearColor];
    _maintableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _maintableview.dataSource = self;
    _maintableview.delegate = self;
    [self.view addSubview:_maintableview];
    
    filepathArr=[[NSMutableArray alloc] init];
    if ([[self.NewRecordArray.firstObject getImagePathList] count] > 0)
    {
        NSArray*fileArr=[NSArray arrayWithArray:[self.NewRecordArray.firstObject getImagePathList]];
        [filepathArr addObject:fileArr];
        //因为查询都是单个点开看，所以这个filepatharr只有一个对象。
        //这边加载的图片数组，是查询状态下，服务器返回的图片，和操作样本无关 本次多样本操作不用管。
    }else
    {
        //这边加载的图片数组，是操作状态下，自己组装的Record对象中读取的,现在改为多样本 数组recordarr形式，需要改。
        for (Record *nowRecord in self.NewRecordArray) {
            NSMutableArray*fileArr=[[NSMutableArray alloc]init];
            if ([[nowRecord getDetailDict] objectForKey:KEY_STEP] &&
                [[[nowRecord getDetailDict] objectForKey:KEY_STEP] count] > 0 &&
                [[[[nowRecord getDetailDict] objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER]){
                fileArr=[NSMutableArray arrayWithArray:[[[nowRecord.getDetailDict objectForKey:KEY_STEP] objectAtIndex:0] objectForKey:KEY_RECORD_ANSWER]];
                //因为保存的时候不可能出现某个样本照片为空，所以必然是依次对应的。
            }
            [filepathArr addObject:fileArr];
            
        }
    }
    


    UIImageView*buttomview=[[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current-50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text= [NSString stringWithFormat:@"当下是第%ld/%ld步",
                 (long)self.NewRecordArray.firstObject.savedStepCount + 1, (long)self.NewRecordArray.firstObject.allStepCount];
    [buttomview addSubview:label];
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1+self.NewRecordArray.count;

    }else{
        return 1;
        
    }
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;//返回标题数组中元素的个数来确定分区的个数
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            return 60;
        }else{
            NSArray*filearr=[filepathArr objectAtIndex:indexPath.row-1];
            if (filearr.count == 0) {
                return (10+50)+10+30;//加30用来写样本号
            }else{
                return (((filearr.count)/5)+1)*(10+50)+10+30;//加30用来写样本号
                
            }
        }
    }else{
        return 50;
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView*headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 18)];
    headview.backgroundColor=[UIColor clearColor];
    return headview;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *strIdentifier = @"strIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strIdentifier];
    
    
    
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                      reuseIdentifier:strIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
        
    
 
    switch (indexPath.section) {
        case 0:
            if (indexPath.row==0) {
                UILabel *titlelab=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, fWidth_Current-40, 60)];
                titlelab.textColor=[UIColor whiteColor];
                titlelab.backgroundColor=[UIColor clearColor];
                titlelab.text=@"5、拍照记录样本大体病理情况";
                UIImageView*lineview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 60, fWidth_Current-20, 1)];
                lineview.backgroundColor=[UIColor colorWithRed:0.91 green:0.91 blue:0.91 alpha:0.3];
                [cell addSubview:titlelab];
                [cell addSubview:lineview];
            }else{
                Record*nowrecord=[self.NewRecordArray objectAtIndex:indexPath.row-1];
                UILabel*recordNameLab=[[UILabel alloc]initWithFrame:CGRectMake(10, 5, fWidth_Current, 30)];
                recordNameLab.backgroundColor=[UIColor clearColor];
                recordNameLab.textColor=[UIColor whiteColor];
                recordNameLab.font=[UIFont systemFontOfSize:16];
                recordNameLab.text=[NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
                [cell addSubview:recordNameLab];
                NSArray*filearr=[filepathArr objectAtIndex:indexPath.row-1];
                
                float juli=(fWidth_Current-20-10-5*50-10)/4;
                for (int i=0; i<filearr.count; i++) {
                    MiloBtn *namebtn=[[MiloBtn alloc]initWithFrame:CGRectMake(10+i%5*(50+juli), i/5*(50+10)+10+30, 50, 50)];
                    namebtn.backgroundColor=[UIColor yellowColor];
                    namebtn.layer.cornerRadius=7;
                    namebtn.clipsToBounds=YES;
                    if ([[filearr objectAtIndex:i] hasPrefix:@"http"]) {
                        [namebtn setImageWithURL:[NSURL URLWithString:[filearr objectAtIndex:i]]
                                        forState:UIControlStateNormal];
                    }else{
                        NSString*filepath=[filearr objectAtIndex:i];
                        UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:filepath];
                        [namebtn setImage:savedImage forState:UIControlStateNormal];
                    }
                    namebtn.tag=i;
                    namebtn.subtag=indexPath.row-1;
                    [namebtn addTarget:self action:@selector(deletephoto:) forControlEvents:UIControlEventTouchUpInside];
                    
                    [cell addSubview:namebtn];
                }
                UIButton * addbtn=[[UIButton alloc]init];
                addbtn.tag = indexPath.row;
                addbtn.frame=CGRectMake(10+filearr.count%5*(50+juli), filearr.count/5*(50+10)+10+30, 50, 50);
                [addbtn setImage:[UIImage imageNamed:@"addphotobtn"] forState:UIControlStateNormal];
                addbtn.backgroundColor=[UIColor clearColor];
                addbtn.layer.cornerRadius=7;
                addbtn.clipsToBounds=YES;
                [addbtn addTarget:self action:@selector(addphoto:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:addbtn];
                
                if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                    addbtn.hidden = YES;
                }else{
                    if (filearr.count<6) {
                        addbtn.hidden = NO;
                        
                    }else{
                        addbtn.hidden = YES;
                        
                    }
                }
            }
            break;
        case 1:{
            cell.backgroundColor=[UIColor clearColor];
            
            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                
                UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
                btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
                btn2.layer.cornerRadius=5;
                [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
                btn2.clipsToBounds=YES;
                [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn2];
            }else{
                UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, (fWidth_Current-30)/2, 50)];
                btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
                btn1.layer.cornerRadius=5;
                [btn1 setTitle:@"取消" forState:UIControlStateNormal];
                btn1.clipsToBounds=YES;
                [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn1];
                UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake((fWidth_Current-30)/2+10, 0, (fWidth_Current-30)/2, 50)];
                btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
                btn2.layer.cornerRadius=5;
                [btn2 setTitle:@"保存" forState:UIControlStateNormal];
                btn2.clipsToBounds=YES;
                [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn2];
            }
        }
            break;
            
        default:
            break;
    }
    return cell;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)addphoto:(UIButton *)btn{
    currentRowIndex = btn.tag;
    //在这里呼出下方菜单按钮项
    myActionSheet = [[UIActionSheet alloc]
                     initWithTitle:nil
                     delegate:self
                     cancelButtonTitle:@"取消"
                     destructiveButtonTitle:nil
                     otherButtonTitles: @"打开照相机", @"从手机相册获取",nil];
    
    [myActionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet==myActionSheet) {
        //呼出的菜单按钮点击后的响应
        if (buttonIndex == myActionSheet.cancelButtonIndex)
        {
            NSLog(@"取消");
        }
        
        switch (buttonIndex)
        {
            case 0:  //打开照相机拍照
                
                [self takeMultiPhoto];
                break;
                
            case 1:  //打开本地相册
                [self multiLocalPhoto];
                break;
        }
        
    }else if(actionSheet == myActionSheet2){
        
        //呼出的菜单按钮点击后的响应
        if (buttonIndex == myActionSheet2.cancelButtonIndex)
        {
            NSLog(@"取消");
        }
        
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            switch (buttonIndex)
            {
                case 0:  //预览图片
                {
                    NSString*photopath=[filepathArr objectAtIndex:nowtag];
                    
                    NSInteger pp=0;
                    pp=[filepathArr indexOfObject:photopath];
                    ShowPicViewController*showfileVC=[[ShowPicViewController alloc]init];
                    showfileVC.urlarr=filepathArr;
                    showfileVC.nowpage=[NSString stringWithFormat:@"%ld",(long)pp];
                    showfileVC.hidesBottomBarWhenPushed=YES;
                    [self.navigationController pushViewController:showfileVC animated:YES];
                }
                    break;
            }
        }else{
            switch (buttonIndex)
            {
                case 0:  //预览图片
                {
                    NSArray*filearr=[filepathArr objectAtIndex:nowRow];
                    NSString*photopath=[filearr objectAtIndex:nowtag];
                    
                    NSInteger pp=0;
                    pp=[filearr indexOfObject:photopath];
                    ShowPicViewController*showfileVC=[[ShowPicViewController alloc]init];
                    showfileVC.urlarr=filearr;
                    showfileVC.nowpage=[NSString stringWithFormat:@"%ld",(long)pp];
                    showfileVC.hidesBottomBarWhenPushed=YES;
                    [self.navigationController pushViewController:showfileVC animated:YES];
                }
                    break;
                    
                case 1:  //删除图片
                {
                    //                    NSMutableArray*assestarr=[selectedAssets objectAtIndex:nowRow];
                    //                    [assestarr removeObjectAtIndex:nowtag];
                    //                    [selectedAssets replaceObjectAtIndex:nowRow withObject:assestarr];
                    
                    NSMutableArray*filearr=[filepathArr objectAtIndex:nowRow];
                    NSString*photopath=[filearr objectAtIndex:nowtag];
                    
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    [fileManager removeItemAtPath:photopath error:nil];
                    [filearr removeObjectAtIndex:nowtag];
                    [filepathArr replaceObjectAtIndex:nowRow withObject:filearr];
                    [_maintableview reloadData];
                }
                    break;
            }
        }
    }
    
}

-(void)takeMultiPhoto
{
    TakeMultiPhotoViewController *vc = [[TakeMultiPhotoViewController alloc] initWithNibName:@"TakeMultiPhotoViewController" bundle:[NSBundle mainBundle]];
    //    if ([[filepathArr objectAtIndex:currentRowIndex-1] count]) {
    //        vc.alreadyArray = [filepathArr objectAtIndex:currentRowIndex-1];
    //    }
    WeakSelf;
    WeakObj(filepathArr);
    vc.nextBlock = ^(NSMutableArray *array) {
        __strong NXFifthStepViewController *strongself = weakSelf;
        NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:[filepathArrWeak objectAtIndex:strongself->currentRowIndex-1]];
        [tmpArray addObjectsFromArray:array];
        [filepathArrWeak replaceObjectAtIndex:strongself->currentRowIndex-1 withObject:tmpArray];
        [strongself->_maintableview reloadData];
    };
    vc.maxcount = 1;
    vc.maxNum = 6-[filepathArr[currentRowIndex-1] count];
    [self presentViewController:vc animated:YES completion:NULL];
}
//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = NO;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:^{}];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}
//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = NO;
    [self presentViewController:picker animated:YES completion:^{}];
}
-(void)multiLocalPhoto
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6-[filepathArr[currentRowIndex-1] count] columnNumber:4 delegate:self pushPhotoPickerVc:YES];
    //    if (selectedAssets.count) {
    //        imagePickerVc.selectedAssets = selectedAssets; // 目前已经选中的图片数组
    //    }
    
    // imagePickerVc.navigationBar.translucent = NO;
    
#pragma mark - 五类个性化设置，这些参数都可以不传，此时会走默认设置
    imagePickerVc.isSelectOriginalPhoto = YES;
    
    [imagePickerVc setUiImagePickerControllerSettingBlock:^(UIImagePickerController *imagePickerController) {
        imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
    }];
    
    // imagePickerVc.photoWidth = 1000;
    
    // 2. Set the appearance
    // 2. 在这里设置imagePickerVc的外观
    // imagePickerVc.navigationBar.barTintColor = [UIColor greenColor];
    // imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
    // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    // imagePickerVc.navigationBar.translucent = NO;
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:31 / 255.0 green:185 / 255.0 blue:34 / 255.0 alpha:1.0];
    imagePickerVc.showPhotoCannotSelectLayer = YES;
    imagePickerVc.cannotSelectLayerColor = [[UIColor whiteColor] colorWithAlphaComponent:0.8];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    /*
     [imagePickerVc setAssetCellDidSetModelBlock:^(TZAssetCell *cell, UIImageView *imageView, UIImageView *selectImageView, UILabel *indexLabel, UIView *bottomView, UILabel *timeLength, UIImageView *videoImgView) {
     cell.contentView.clipsToBounds = YES;
     cell.contentView.layer.cornerRadius = cell.contentView.tz_width * 0.5;
     }];
     */
    
    // 3. Set allow picking video & photo & originalPhoto or not
    // 3. 设置是否可以选择视频/图片/原图
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.allowPickingGif = NO;
    imagePickerVc.allowPickingMultipleVideo = NO; // 是否可以多选视频
    
    // 4. 照片排列按修改时间升序
    imagePickerVc.sortAscendingByModificationDate = YES;
    
    // imagePickerVc.minImagesCount = 3;
    // imagePickerVc.alwaysEnableDoneBtn = YES;
    
    // imagePickerVc.minPhotoWidthSelectable = 3000;
    // imagePickerVc.minPhotoHeightSelectable = 2000;
    
    /// 5. Single selection mode, valid when maxImagesCount = 1
    /// 5. 单选模式,maxImagesCount为1时才生效
    imagePickerVc.showSelectBtn = NO;
    
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    
    // 设置是否显示图片序号
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.photoWidth = ScreenWidth/2;
    
#pragma mark - 到这里为止
    
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image1 = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        UIImage* image=[image1 fixOrientation];

        NSData *data;
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        NSString*nowtime=[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
        NSString*picturename=[NSString stringWithFormat:@"/%@.png",nowtime];

        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:picturename] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        NSString* filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  picturename];
        [filepathArr addObject:filePath];
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        [_maintableview reloadData];
        
        
        
    } 
    
}
-(void)deletephoto:(MiloBtn *)sender{
    
    if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
        myActionSheet2 = [[UIActionSheet alloc]
                          initWithTitle:nil
                          delegate:self
                          cancelButtonTitle:@"取消"
                          destructiveButtonTitle:nil
                          otherButtonTitles: @"预览图片",nil];
    }else{
        myActionSheet2 = [[UIActionSheet alloc]
                          initWithTitle:nil
                          delegate:self
                          cancelButtonTitle:@"取消"
                          destructiveButtonTitle:nil
                          otherButtonTitles: @"预览图片", @"删除该图片",nil];
    }
    
    [myActionSheet2 showInView:self.view];
    
    nowtag=sender.tag;
    nowRow=sender.subtag;
}
-(void)saveClick{
    for (int i=0;i<filepathArr.count;i++) {
        NSArray*filearr=[filepathArr objectAtIndex:i];
        if (filearr.count<=0) {
            Record*nowrecord=[self.NewRecordArray objectAtIndex:i];
            NSString*msg=[NSString stringWithFormat:@"请至少为样本%@选择一张图片",nowrecord.recordId];
            [self.view makeToast:msg];
            return;
        }
    }
    for (Record *model in self.NewRecordArray) {
        NSInteger index =[self.NewRecordArray indexOfObject:model];
        NSArray *filearr=[filepathArr objectAtIndex:index];
        [self creatDetailDict:model and:filearr];
        model.savedStepCount = 5;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [model update];
        });
    }
    
    if (self.NewRecordArray.firstObject.type==2) {
        NXSeventhStepViewController *ZLSixthStepVC = [[NXSeventhStepViewController alloc] init];
        ZLSixthStepVC.NewRecordArray = self.NewRecordArray;
        [self.navigationController pushViewController:ZLSixthStepVC animated:YES];

    }else if(self.NewRecordArray.firstObject.type==3){
        NXSixthStepViewController *NXSixthStepVC = [[NXSixthStepViewController alloc] init];
        NXSixthStepVC.NewRecordArray = self.NewRecordArray;
        [self.navigationController pushViewController:NXSixthStepVC animated:YES];
    }

}

-(void)creatDetailDict:(Record *)model and:(NSArray *)arr{
    
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"5、拍照记录样本大体病理情况", KEY_RECORD_QUESTION,
                                  TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                  arr, KEY_RECORD_ANSWER, nil];
    
    NSArray *qustionArr = [NSArray arrayWithObjects:questionDict, nil];
    
    NSMutableDictionary *tempDict = [model getDetailDict];
    [tempDict setObject:qustionArr forKey:KEY_STEP];
    [model setDetailDict:tempDict];
    NSLog(@"tempDict %@", tempDict);
    model.recordDetail = [tempDict JSONString];

  
}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}

-(void)nextStepClick{
    for (Record *model in self.NewRecordArray) {
        model.savedStepCount = 5;
    }

    if (self.NewRecordArray.firstObject.type==2) {
        NXSeventhStepViewController *ZLSixthStepVC = [[NXSeventhStepViewController alloc] init];
        ZLSixthStepVC.NewRecordArray = self.NewRecordArray;
        ZLSixthStepVC.fromtype = @"search";
        [self.navigationController pushViewController:ZLSixthStepVC animated:YES];
    }else if(self.NewRecordArray.firstObject.type==3){
        NXSixthStepViewController *NXSixthStepVC = [[NXSixthStepViewController alloc] init];
        NXSixthStepVC.NewRecordArray = self.NewRecordArray;
        NXSixthStepVC.fromtype = @"search";
        [self.navigationController pushViewController:NXSixthStepVC animated:YES];
    }
}


- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    if (selectedAssets.count == 0) {
        //        selectedAssets = [NSMutableArray arrayWithCapacity:0];
    }
    if (selectedAssets.count > currentRowIndex-1) {
        [selectedAssets replaceObjectAtIndex:currentRowIndex-1 withObject:assets];
    }else
    {
        [selectedAssets addObject:assets];
    }
    selectedAssets = [NSMutableArray arrayWithArray:assets];
    NSArray *selectedPhotos = [NSMutableArray arrayWithArray:photos];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),^{
        NSMutableArray *pathArrays = [NSMutableArray arrayWithCapacity:0];
        for (UIImage *image in selectedPhotos) {
            NSInteger index = [selectedPhotos indexOfObject:image];
            NSData *data = UIImagePNGRepresentation(image);
            [pathArrays addObject:[self getPath:data index:index]];
        }
        if (filepathArr.count == 0) {
            filepathArr = [NSMutableArray arrayWithCapacity:0];
        }
        if (filepathArr.count > currentRowIndex-1) {
            NSMutableArray *tmpArray = [filepathArr objectAtIndex:currentRowIndex-1];
            [tmpArray addObjectsFromArray:pathArrays];
            [filepathArr replaceObjectAtIndex:currentRowIndex-1 withObject:tmpArray];
        }else
        {
            [filepathArr addObject:pathArrays];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_maintableview reloadData];
        });
    });
    
    
    
    
}

-(NSString *)getPath:(NSData *)data index:(NSInteger)index
{
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
    
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //把刚刚图片转换的data对象拷贝至沙盒中
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSDateFormatter *formatDate = [[NSDateFormatter alloc] init];
    [formatDate setDateFormat:@"yyyyMMddhhmmssSSS"];
    NSString *time = [formatDate stringFromDate:date];
    NSString *ImagePath = [NSString stringWithFormat:@"/%@%@-%i.png",[DataManage getObjectForKey:@"phone"],time,index];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:ImagePath] contents:data attributes:nil];
    
    //得到选择后沙盒中图片的完整路径
    NSString *filePath = [[NSString alloc] initWithFormat:@"%@%@", DocumentsPath, ImagePath];
    return filePath;
    
}
// Decide album show or not't
// 决定相册显示与否
- (BOOL)isAlbumCanSelect:(NSString *)albumName result:(PHFetchResult *)result {
    /*
     if ([albumName isEqualToString:@"个人收藏"]) {
     return NO;
     }
     if ([albumName isEqualToString:@"视频"]) {
     return NO;
     }*/
    return YES;
}

// Decide asset show or not't
// 决定asset显示与否
- (BOOL)isAssetCanSelect:(PHAsset *)asset {
    /*
     switch (asset.mediaType) {
     case PHAssetMediaTypeVideo: {
     // 视频时长
     // NSTimeInterval duration = phAsset.duration;
     return NO;
     } break;
     case PHAssetMediaTypeImage: {
     // 图片尺寸
     if (phAsset.pixelWidth > 3000 || phAsset.pixelHeight > 3000) {
     // return NO;
     }
     return YES;
     } break;
     case PHAssetMediaTypeAudio:
     return NO;
     break;
     case PHAssetMediaTypeUnknown:
     return NO;
     break;
     default: break;
     }
     */
    return YES;
}
@end
